package ru.compscicenter.databases.zaikina.common;

import ru.compscicenter.databases.zaikina.common.commands.*;

import java.util.ArrayList;

public class DatabaseController {

    private ManagedObject node;
    private final DatabaseManager manager;
    private Thread thread;

    private ManagerEventListener listener = new Listener();
    private SysCommandBuffer buffer;// = new SysCommandBuffer();

    public DatabaseController(ManagedObject node) {
        this.node = node;
        this.buffer = new SysCommandBuffer(node.getNodeId());
        manager = new DatabaseManager(node, listener);
        thread = new Thread(manager);
        thread.start();
    }

    private class Listener implements ManagerEventListener {

        public void onReady(ManagerEvent event) {
            synchronized (this) {
                node = event.getUpdatedData(node);
            }
        }
    }

    public SysCommand<?, ?> processCommand(SysCommand<?, ?> command) {
        if (command == null) {
            return new EmptyCommand(SysCommandType.Error);
        }

        if (SysCommandType.isEasyCommand(command.getType())) {
            return node.process(command);
        }

        buffer.add(command);
        synchronized (manager) {
            buffer = manager.setBuffer(buffer);
        }
        return new EmptyCommand(SysCommandType.Success);
    }

    public void stop() {
         thread.interrupt();
    }
}
